/*
 * HC_SR04.h
 * 
 *  注意电源 5V
 */
#ifndef HC_SR04_H
#define HC_SR04_H

#include <stdio.h>
#include <sys/time.h>
#include <wiringPi.h>

class Sonic{
	
	char PIN_TRIG;
	char PIN_ECHO;
	
	public:
	Sonic(char trig, char echo) : PIN_TRIG(trig), PIN_ECHO(echo) {}
	
	void init(void)
	{
		pinMode(PIN_ECHO, INPUT);
		pinMode(PIN_TRIG, OUTPUT);
		digitalWrite(PIN_TRIG,0);
	}

	float value(void)
	{
		struct timeval tv;
		unsigned int start=0,end=0;
		
		//发射10us以上的信号
		digitalWrite(PIN_TRIG,1);
		delayMicroseconds(10);
		digitalWrite(PIN_TRIG,0);
		
		//等待接收
		while(digitalRead(PIN_ECHO)==0);
		gettimeofday(&tv,NULL);
		start = tv.tv_usec;
		while(digitalRead(PIN_ECHO)==1);
		gettimeofday(&tv,NULL);
		end = tv.tv_usec;
		return (float)((end-start)*0.017); //单位cm
	}

};

#endif
